package com.xiaotu.code.service.quartz;

import java.io.Serializable;
import java.util.Calendar;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.CronTriggerBean;

import com.xiaotu.code.model.quartz.QuartzCronExpression;
import com.xiaotu.code.system.ServiceException;

/**
 * 从数据库初始化trigger.
 * 
 * @author chenxiangrong
 */
public class DefineDbCronTriggerBean extends CronTriggerBean implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4392408695371504065L;
	public static final String NERVER_RUN_EXPRESS = "30 0 0 1 1 ? %s";
	@Autowired
	private QuartzCronExpressionService quartzCronExpressionService;

	@Override
	public void afterPropertiesSet() throws Exception {

		super.afterPropertiesSet();
		// 获取数据配置
		QuartzCronExpression expression = quartzCronExpressionService.getQuartzCronExpression(super.getName());
		if (expression == null) {
			throw new ServiceException("任务管理器" + super.getName() + "未配置,请到表QUARTZ_CRON_EXPRESSION中添加配置");
		}
		// 如果是停止状态，则获取一个永远达不到的日期
		if (QuartzCronExpressionService.STOP_STATUS.equals(expression.getStatus())) {
			super.setCronExpression(getNeverNeverFireExpression());
		} else {
			super.setCronExpression(expression.getExpression());
		}
	}

	/**
	 * 获取一个永远达不到的执行日期：当前年份+10年的1月1日凌晨30秒.
	 * 
	 * @return
	 */
	private String getNeverNeverFireExpression() {

		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.YEAR, 10);
		int year = cal.get(Calendar.YEAR);
		return String.format("30 0 0 1 1 ? %s", year);
	}
}